<template>
    <div class="system-index">
        <el-card class="page-card">
            <div class="page-header">
                <h2>骑手管理</h2>
                <el-button type="success" @click="showAddDialog" icon="Plus">新增骑手</el-button>
            </div>

            <!-- 查询表单 -->
            <el-form :model="rider" ref="ruleFormRef" label-width="120px" label-position="right" class="search-form">
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="骑手姓名" prop="name">
                            <el-input v-model="rider.name" placeholder="请输入骑手姓名" clearable/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="工作状态" prop="gzzt">
                            <el-select v-model="rider.gzzt" placeholder="请选择工作状态" clearable>
                                <el-option label="空闲" value="空闲"/>
                                <el-option label="忙碌" value="忙碌"/>
                                <el-option label="休息" value="休息"/>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="手机号" prop="phone">
                            <el-input v-model="rider.phone" placeholder="请输入手机号" clearable/>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="工作收入" prop="gzsr">
                            <el-input v-model="rider.gzsr" placeholder="请输入工作收入" clearable/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="评分" prop="mark">
                            <el-input v-model="rider.mark" placeholder="请输入评分" clearable/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="认证状态" prop="state">
                            <el-select v-model="rider.state" placeholder="请选择认证状态" clearable>
                                <el-option label="待认证" value="待认证"/>
                                <el-option label="已认证" value="已认证"/>
                                <el-option label="认证失败" value="认证失败"/>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="24" class="search-buttons" style="display: flex; justify-content: center; margin-top: 5px;">
                        <el-space size="large">
                            <el-button type="primary" @click="doList" icon="Search">查询</el-button>
                            <el-button type="default" @click="doFormReset" icon="Refresh">重置</el-button>
                        </el-space>
                    </el-col>
                </el-row>
            </el-form>

            <!-- 数据表格 -->
            <el-table :data="tableData" stripe hover-row border style="width: 100%" class="data-table">
                <el-table-column type="index" label="序号" width="80" align="center"/>
<!--                <el-table-column prop="id" label="ID" align="center"/>-->
                <el-table-column prop="name" label="骑手姓名" align="center"/>
                <el-table-column prop="phone" label="手机号" align="center"/>
                <el-table-column prop="gzzt" label="工作状态" align="center"/>
                <el-table-column prop="gzsr" label="工作收入" align="center"/>
                <el-table-column prop="mark" label="评分" align="center"/>
                <el-table-column prop="state" label="认证状态" align="center"/>
                <el-table-column label="操作" width="240" align="center">
                    <template #default="scope">
                        <el-space size="small">
                            <el-button type="primary" size="small" @click="showDetailPage(scope.row)" icon="View">详情</el-button>
                            <el-button type="warning" size="small" @click="showUpdateDialog(scope.row)" icon="Edit">更新</el-button>
                            <el-button type="danger" size="small" @click="doDelete(scope.row.id)" icon="Delete">删除</el-button>
                        </el-space>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页控件 -->
            <div class="pagination">
                <el-pagination
                    style="float: left;"
                    layout="total, sizes, prev, pager, next, jumper"
                    :page-sizes="[5, 10, 20, 50]"
                    v-model:current-page="page.pageNum"
                    v-model:page-size="page.pageSize"
                    :total="page.total"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />
            </div>

        </el-card>

        <!-- 新增对话框 -->
        <el-dialog v-model="addDialogVisible" title="新增骑手" width="50%" top="10vh" destroy-on-close>
            <add-page @flushPage="doFlushPage" @closeDialog="addDialogVisible = false"/>
        </el-dialog>

        <!-- 更新对话框 -->
        <el-dialog v-model="updateDialogVisible" title="更新骑手" width="50%" top="10vh" destroy-on-close>
            <update-page ref="updatePageRef" @flushPage="doFlushPage" @closeDialog="updateDialogVisible = false"/>
        </el-dialog>

        <!-- 详情页面 -->
        <detail-page ref="detailPageRef"/>
    </div>
</template>


<style scoped>
.system-index {
    padding: 20px;
}

.page-card {
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    border-radius: 8px;
    overflow: hidden;
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    border-bottom: 1px solid #f0f0f0;
    margin-bottom: 20px;
}

.page-header h2 {
    margin: 0;
    font-size: 20px;
    color: #303133;
}

.search-form {
    padding: 0 20px 20px;
}

.search-buttons {
    display: flex;
    align-items: center;
    margin-top: -18px;
}

.data-table {
    margin: 0 20px 20px;
}

.pagination {
    margin: 20px;
    padding: 10px 0;
    background: white;
    border-top: 1px solid #ebeef5;
    position: relative; /* 改为相对定位 */
    z-index: 1; /* 确保不被遮挡 */
}
</style>

<script setup lang="ts">
import {nextTick, onMounted, ref} from 'vue';
import {ElMessage, FormInstance} from 'element-plus'
import axios from 'axios';
import DetailPage from './DetailPage.vue';
import AddPage from './AddPage.vue';
import UpdatePage from './UpdatePage.vue';

//------------------------- form 表单 -----------------------------
// 查询条件
const rider = ref({
    name: '',
    phone: '',
    gzzt: '',
    gzsr: '',
    mark: '',
    state: ''
})
// 表单对象，在 <el-form> 标签上通过 ref 绑定此对象
const ruleFormRef = ref<FormInstance>()
// 表单重置
const doFormReset = () => {
    ruleFormRef.value?.resetFields()
}

// -------------------------- table 表格 ----------------------------
// 表格数据
const tableData = ref([]);
// 分页信息
const page = ref({
    pageNum: 1,     // 当前页码
    pageSize: 5,   // 每页显示的记录数
    pages: 0,       // 总页数
    total: 0        // 总记录数
})
const handleSizeChange = (val: number) => {
    page.value.pageSize = val;
    page.value.pageNum = 1; // 重置到第一页
    doList();
};

// 处理页码变化
const handleCurrentChange = (val: number) => {
    page.value.pageNum = val;
    doList();
};
// 分页重置
const doPageReset = () => {
    page.value.pageNum = 1;
    page.value.pageSize = 5;
    page.value.pages = 0;
    page.value.total = 0;
}

//--------------------------- CRUD -----------------------------
// 查询
const loading = ref(false); // 加载状态

const doList = async () => {
    loading.value = true;
    try {
        // 构建查询参数，包含分页信息和查询条件
        const params = {
            ...rider.value,
            pageNum: page.value.pageNum,
            pageSize: page.value.pageSize
        };
        const {data} = await axios.get('/api/rider/list', { params });
        console.log('API Response:', data);

        // 确保处理正确的分页数据结构
        if (data && data.data) {
            // 标准分页响应结构 { data: { list: [], total: 100 } }
            tableData.value = data.data.list || [];
            page.value.total = data.data.total || 0;
        } else if (data && data.list) {
            // 兼容结构 { list: [], total: 100 }
            tableData.value = data.list;
            page.value.total = data.total || 0;
        } else {
            // 其他结构处理
            tableData.value = Array.isArray(data) ? data : [];
            page.value.total = tableData.value.length;
        }

        console.log('表格数据:', tableData.value);
        console.log('分页信息:', page.value);
    } catch (error) {
        console.error('查询失败:', error);
        ElMessage.error('获取数据失败');
    }
}

// 删除
const doDelete = async(id) => {
    const { data} = await axios.delete('/api/rider/' + id);
    if (data > 0) {
        doFlushPage();		// 删除成功，查询刷新表格数据
        ElMessage.success('删除成功');
    } else {
        ElMessage.error('删除失败');
    }
}

// 刷新页面：表单重置、分页重置、重新查询
const doFlushPage = () => {
    doFormReset();
    doPageReset()
    doList();
}

//--------------------------- 页面初始化 -----------------------------
onMounted(() => {
    doList();	// 页面初始化查询显示
});

//--------------------------- 详显 页面-----------------------------
// 详显组件引用
const detailPageRef = ref();
const showDetailPage = (obj) => {
    detailPageRef.value.handleDetailData(obj);
}

//--------------------------- 新增 对话框 -----------------------------
const addDialogVisible = ref(false);    // 控制新增对话框的显示和隐藏(true:显示,false:隐藏)
const showAddDialog = () => {
    addDialogVisible.value = true;
}

//--------------------------- 更新 对话框 -----------------------------
const updateDialogVisible = ref(false); // 控制更新对话框的显示和隐藏(true:显示,false:隐藏)
// 更新组件的引用, 用于调用更新页面的方法,在 <update-page> 标签上通过 ref 属性绑定该引用
const updatePageRef = ref();
const showUpdateDialog = (obj) => {
    updateDialogVisible.value = true;
    nextTick(() => {
        // 调用更新页面的方法 handleUpdateData，将数据传递给更新页面
        updatePageRef.value.handleUpdateData(obj);
    })
}
</script>